package com.rajaev.dtu.tractor.infrastructure.helper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @Created with IDEA
 * @author: tianjie
 * @Date:2019/5/6
 * @Time:17:53
 */
@Slf4j
public class BeanUtils extends org.springframework.beans.BeanUtils {

    /**
     * 利用反射，效率很高
     * JavaBean转Map
     *
     * @param obj
     * @return
     */
    public static Map<String, Object> beanToMap(Object obj) {
        Map<String, Object> params = new HashMap<String, Object>(1200);
        try {
            Field[] declaredFields = obj.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                params.put(field.getName(), field.get(obj));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return params;
    }

    public static void copyNotNullProperties(Object source, Object target, String... ignoreProperties) {
        try {
            String[] notNullProperties = getNullPropertyNames(target);


            List<String> notNullList = Arrays.asList(notNullProperties);
            List<String> ignoreList = Arrays.asList(ignoreProperties);
            notNullList.addAll(ignoreList);

            copyProperties(source, target, notNullList.toArray(new String[]{}));
        } catch (Exception e) {
            log.error("",e);
        }

    }

    /**
     * @param source 要拷贝的对象
     * @return
     * @Description <p>获取到对象中属性为null的属性名  </P>
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null)
                emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }


    public static void main(String[] args) {
        String x = "123";
        int a = Integer.parseInt(x, 16);
        System.out.println(a);
    }


}
